package yunjiao.javatutorials.guava.concurrent.time;

import yunjiao.javatutorials.guava.concurrent.ForwardingLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * 带超时监控的锁
 *
 * @author yangyunjiao
 */
public class TimeoutMonitoringLock extends ForwardingLock {
    private final Lock delegate;
    private final long timeoutThreshold; // 超时阈值(毫秒)

    public TimeoutMonitoringLock(Lock delegate, long timeoutThreshold) {
        this.delegate = delegate;
        this.timeoutThreshold = timeoutThreshold;
    }

    @Override
    protected Lock delegate() {
        return delegate;
    }

    @Override
    public void lock() {
        long startTime = System.currentTimeMillis();
        super.lock();
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        if (duration > timeoutThreshold) {
            System.err.println("WARNING: Lock acquisition took " + duration + "ms, exceeding threshold " + timeoutThreshold + "ms");
        }
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        boolean result = super.tryLock(time, unit);
        long endTime = System.currentTimeMillis();

        if (result) {
            long duration = endTime - startTime;
            if (duration > timeoutThreshold) {
                System.err.println("WARNING: tryLock took " + duration + "ms");
            }
        }

        return result;
    }
}
